import {useReducer} from 'react'


const initialState = {value: 'luogege',list:[]};

  function reducer(state, action) {
    switch (action.type) {
      case 'add':
        // console.log(state,state.value);
        if(state.value === "") {
          alert("请输入内容")
          return state
        }
        state.list.push(state.value) 
        state.value = "";
        return {...state,list: state.list}
      case 'dec':
        // console.log(state,action.index);
        state.list.splice(action.index,1)
        return {...state,list: state.list}
      case 'change':
        return {...state,value: action.value}
      default:
        throw new Error();
    }
  }

function App(){
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <div>
    <h3>这里是useReducer</h3>
        <div>
          <input type="text" 
            value={state.value} 
            onChange={(e) => dispatch({value: e.target.value,type: 'change'})}

            />
          <button
           onClick={() => dispatch({type: 'add'})}
           >提交</button>
        </div>
        <ul>
          {
            state.list.map((item, index)=>{
              return (<li key={index}>{item} <button onClick={()=> dispatch({index,type: 'dec'})}>X</button></li>)
            })
          }
        </ul>
    </div>
  )
  
}

export default App